<template>
  <div class="project-type-person-manage">
    <div class="project-type-person-manage-title">
      <i18n path="common.projectManage.detail.projectTotalCount">
        <span place="count" class="number">{{ staffList.length }}</span>
      </i18n>
      <el-button v-if="editProjectAuth" type="primary" size="mini" icon="el-icon-plus" @click="handleClickAddStaff">{{ $t('calendar.detail.addPeople') }}</el-button>

      <span v-if="!listLoading && staffList.length < 2" class="popover"><el-popover :value="isPopover" popper-class="popperClass" placement="bottom" width="216" :content="$t('common.projectManage.detail.addPersonTip')"> </el-popover></span>
    </div>
    <div class="project-type-person-manage-content">
      <div class="project-type-person-manage-content-list" v-loading="listLoading">
        <div class="project-type-person-manage-content-list-item" v-for="item in staffList" :key="item.userId">
          <img v-user="item.userId" :src="head(item.head)" alt="" class="img" />
          <span v-user="item.userId" class="title-text">{{ item.displayName }}</span>
          <i v-if="!item.projectManagerFlag && editProjectAuth" class="iconfont icon-close" @click="handleClickDeleteStaff(item)"></i>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser';
import { getMemberList, getMemberAdd, getMemberRemove, getCheckTaskManger } from '@src/api/ProjectManage.ts';

import { toast } from '@src/util/platform';
import { MessageBox } from 'element-ui';
import i18n from '@src/locales';

/* images */
import { getOssUrl } from '@src/util/assets'
const DefaultHead = getOssUrl('avatar.png')

export default {
  name: 'project-type-person-manage',
  props: {
    templateId: {
      type: String | Number,
      default: '',
    },
    projectId: {
      type: String | Number,
      default: '',
    },
    // 权限
    btnAuth: {
      type: Object,
      default: () => ({}),
    },
    isPersonnelTab: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      staffList: [],
      listLoading: false,
    };
  },
  computed: {
    editProjectAuth() {
      return this.btnAuth?.editProjectAuth || false;
    },
    isPopover() {
      return this.isPersonnelTab
    }
  },
  mounted() {
    this.fetchStaffList();
  },
  methods: {
    head(src) {
      if (!src) return DefaultHead
      return src
    },
    // 获取成员列表
    async fetchStaffList() {
      try {
        this.listLoading = true;
        let ret = await getMemberList({
          projectId: this.projectId,
        });

        const { success, data, message } = ret;
        if (!success) return toast(message, 'error');

        this.staffList = data || [];
      } catch (err) {
        console.log('error => fetchStaffList', err);
      } finally {
        this.listLoading = false;
      }
    },
    // 添加人员
    handleClickAddStaff() {
      const selectUser = (this.staffList || []).map(item => {
        return {
          displayName: item.displayName,
          userId: item.userId,
          staffId: item.staffId,
          disabled: item.projectManagerFlag
        };
      });

      let options = {
        max: -1, // [选填]最大人数：当值小于等于0或者不填时，不对选择人数做限制，max值为1时单选，大于1时多选
        selectedUsers: selectUser, // [选填] 已选人员 每个人员必须包括userId,displayName,staffId,head这四个属性，只有带max大于1时生效
        mode: BaseSelectUserModeEnum.Filter,
      };

      this.$fast.select.multi
        .user(options)
        .then(res => {
          if (res.status != 0 || !res.data) return;

          let list = res.data.users || [];

          let userIds = list.map(item => item.userId);

          const params = {
            projectId: this.projectId,
            userIds,
          };

          // 获取任务负责人
          getCheckTaskManger({ ...params }).then(res => {
            if (!res.success) {
              return toast(res.message, 'error');
            }

            if (res.data?.length > 0) {
              // 有任务负责人二次弹框
              this.addStaffDialog(res.data, params);
            } else {
              this.chooseStaffFunc(params);
            }
          });
        })
        .catch(err => {
          console.error(err);
        });
    },
    chooseStaffFunc(params) {
      try {
        getMemberAdd({ ...params }).then(res => {
          const { success, data, message } = res;
          if (!success) return toast(message, 'error');

          toast(i18n.t('common.base.tip.addSuccess'), 'success');

          this.fetchStaffList();
        });
      } catch (err) {
        console.log('error => chooseUserFunc', err);
      }
    },
    // 添加二次确认弹框 - 待开发
    addStaffDialog(displayName, params) {
      MessageBox.confirm(this.$t('common.projectManage.detail.deletePersonTip1', { userName: displayName }), this.$t('common.base.toast'), {
        confirmButtonText: i18n.t('common.base.makeSure'),
        cancelButtonText: i18n.t('common.base.cancel'),
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;

            this.chooseStaffFunc(params);
            instance.confirmButtonLoading = false;
            done();
          } else {
            this.fetchStaffList();
            instance.confirmButtonLoading = false;
            done();
          }
        },
      });
    },
    // 删除成员
    handleClickDeleteStaff(row) {
      let params = {
        projectId: this.projectId,
        userIds: [row.userId],
      };

      let content = '';
      // 任务负责人
      if (row.taskManagerFlag) {
        content = i18n.t('common.projectManage.detail.deletePersonTip1', { userName: row.displayName });
      } else {
        content = i18n.t('common.projectManage.detail.deletePersonTip');
      }

      MessageBox.confirm(content, this.$t('common.base.toast'), {
        confirmButtonText: i18n.t('common.base.makeSure'),
        cancelButtonText: i18n.t('common.base.cancel'),
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            getMemberRemove({ ...params }).then(res => {
              instance.confirmButtonLoading = false;

              if (!res.success) {
                return toast(res.message, 'error');
              }

              toast(i18n.t('common.base.tip.deleteSuccess'), 'success');

              done();

              this.fetchStaffList();
            });
          } else {
            instance.confirmButtonLoading = false;
            done();
          }
        },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.project-type-person-manage {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  &-title {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
    .number {
      color: $color-primary-light-6;
      margin: 0 4px;
    }
    .popover {
      position: absolute;
      right: 216px;
      top: 34px;
      z-index: 10!important;
    }
    ::v-deep .el-button--mini {
      border-radius: 4px;
    }
  }
  &-content {
    flex: 1;
    overflow: auto;
    &-list {
      display: flex;
      flex-wrap: wrap;
      &-item {
        display: flex;
        align-items: center;
        background: #f5f5f5;
        border-radius: 4px;
        margin-right: 16px;
        margin-bottom: 16px;
        padding: 4px 8px 4px 4px;
        cursor: pointer;

        .img {
          display: inline-block;
          width: 24px;
          height: 24px;
          margin-right: 4px;
          border-radius: 50%;
        }
        .title-text {
          display: inline-block;
          max-width: 320px;
          color: #595959;
          font-size: 14px;
          font-family: PingFangSC-Regular, PingFang SC;
          margin-right: 8px;
          @include text-ellipsis();
        }
        .icon-close {
          &:hover {
            color: $color-primary-light-6;
          }
        }
      }
    }
  }
}
</style>